package com.yushealth.prostate.fingerdanceforprostate;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jesusm.holocircleseekbar.lib.HoloCircleSeekBar;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;

import app.minimize.com.seek_bar_compat.SeekBarCompat;

public class MainActivity extends AppCompatActivity {

    // 请求码
    private final int REQUEST_CLOCK = 0;
    private final int REQUEST_LEVEL = 1;
    private final int REQUEST_MUSIC = 2;
    // 息
    final Integer BREATH[] = {5000, 15000, 25000, 35000, 45000, 55000, 65000, 75000, 90000, 100000};
    private Integer breath_cur;

    // 进度条长度
    private final int PROGRESSBAR_LENGTH = 100;

    // 闹钟
    private ArrayList<PendingIntent> clockArray;
    Context context;
    AlarmManager alarmMgr;

    // 按返回键当前时间
    private long currentBackPressedTime = 0;
    // 数据定义
    private HashMap<String, String> ClockData;
    private HashMap<String, Integer> BreathData;
    private HashMap<String, String> MusicData;
    private HashMap<String, Integer> ProfileData;

    Resources resources;
    Locale locale;  // locale

    // 标志
    enum Status {
        PLAY, PAUSE, STOP
    }

    ;
    private Status status = Status.STOP;

    //组件
    ImageButton btnPlay;
    ImageButton btnPause;
    ImageButton btnStop;

    ImageView imgFinger;
    ImageView imgMusic;
    TextView txtFingerStage;

    // section: 呼吸
    TextView txtBreathStage;
    TextView txtBreathCount;

    // main data
    private SeekBar seekBar;
    private int pos;

    // 吸气，呼气间隔
    private int inhale;
    private int hold;
    private int exhale;
    private int inhale_count;
    private int hold_count;
    private int exhale_count;

    private CountDownTimer timer;
    private int division_up; // 进度条分度值 1
    private int division_back; // 进度条分度值 1

    private enum Stage {INHALE, HOLD, EXHALE}

    private Stage stage = Stage.INHALE;

    private boolean music_is_on = false;  // 默认关闭音乐

    // 手指阶段
    private ArrayList<FingerAction> fingers;  // 0, 1
    private ArrayList<SeekBarCompat> seekBars;  // 0, 1
    private ArrayList<TextView> action_left;  // 0, 1
    private int fingerIndex;
    private FingerAction finger_cur;

    // 进度条：动作计数
    private SeekBarCompat barAction_1;
    private SeekBarCompat barAction_2;
    // 动作次数剩余
    private TextView action_left_1;
    private TextView action_left_2;

    // 进度条：动作持续
    HoloCircleSeekBar circleSeekBar;
    int action_length;

    // 背景音乐
    private boolean mIsBound = false;
    private MusicService mServ;
    private ServiceConnection Scon;
    private boolean is_new_music = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar;
        if ((actionBar = getSupportActionBar()) != null) {
            actionBar.setDisplayShowTitleEnabled(false);
        }
        // --- my code begin ---

        // 读取设置数据
        readData();
        // 闹钟变量初始化
        clockArray = new ArrayList<>();
        context = getApplication();
        alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
        // 启用闹钟
        if (ClockData.get("clock_is_on").equals("true")) {
            ClockAlarm();
        }

        // 进度： 呼吸
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        seekBar.setMax(PROGRESSBAR_LENGTH);
        seekBar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        btnPlay = (ImageButton) findViewById(R.id.btnPlay);
        btnPause = (ImageButton) findViewById(R.id.btnPause);
        // Button: stop
        btnStop = (ImageButton) findViewById(R.id.btnStop);
        state_button_update(0, 0, 1);

        imgMusic = (ImageView) findViewById(R.id.musicOnOff);

        txtBreathStage = (TextView) findViewById(R.id.txtBreathStage);
        txtBreathCount = (TextView) findViewById(R.id.txtBreathCount);

        txtFingerStage = (TextView) findViewById(R.id.txtFingerStage);  // 阶段： 手指
        imgFinger = (ImageView) findViewById(R.id.imgFinger);
        // 取得资源
        resources = getResources();

        // 动作次数计数
        barAction_1 = (SeekBarCompat) findViewById(R.id.bar_action_1);
        barAction_2 = (SeekBarCompat) findViewById(R.id.bar_action_2);
        barAction_1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });
        barAction_2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });

        action_left_1 = (TextView) findViewById(R.id.action_left_1);
        action_left_2 = (TextView) findViewById(R.id.action_left_2);

        seekBars = new ArrayList<>();
        seekBars.add(barAction_1);
        seekBars.add(barAction_2);

        action_left = new ArrayList<>();
        action_left.add(action_left_1);
        action_left.add(action_left_2);
        // 进度条： 动作
        circleSeekBar = (HoloCircleSeekBar) findViewById(R.id.circleSeekBar);
        if (circleSeekBar != null) {
            circleSeekBar.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    return true;
                }
            });
            if (ProfileData.get("level") < 2) {
                action_length = 90; // 动作持续90秒
            } else {
                action_length = 180; // 1,2级时，动作持续180秒
            }
            circleSeekBar.setMax(action_length);
        }

        // 动作： 手指
        fingers = new ArrayList<>();
        fingers.add(new FingerAction(this, 9, action_length,  // 9
                new int[]{
                        R.drawable.s_0_b0,
                        R.drawable.s_0_b1,
                        R.drawable.s_0_b2,
                },
                new int[]{
                        R.drawable.s_0_b3,
                        R.drawable.s_0_b4,
                        R.drawable.s_0_b5,
                        R.drawable.s_0,
                }));
        fingers.add(new FingerAction(this, 3, action_length,  // 3
                new int[]{
                        R.drawable.s_1_b0,
                },
                new int[]{
                        R.drawable.s_1_b1,
                        R.drawable.s_0,
                }));

        // 取 locale
        locale = Locale.getDefault();

        // main
        timer = new CountDownTimer(1000, 100) {
            @Override
            public void onTick(long l) {
                if (status == Status.PAUSE) return;
                // 呼吸
                switch (stage) {
                    case INHALE:  // 吸气
                        inhale_count -= 100;
                        pos++;
                        // 更新进度条 吸气
                        seekBar.setProgress(pos * division_up);

                        txtBreathCount.setText(String.valueOf(inhale_count / 1000.0));
                        txtBreathStage.setText(R.string.m_info_inhale);

                        if (inhale_count == 0) {
                            inhale_count = inhale * 1000;
                            stage = Stage.HOLD;
                        }
                        //
                        break;
                    case HOLD:  // 摒息
                        hold_count -= 100;
                        txtBreathCount.setText(String.valueOf(hold_count / 1000.0));
                        txtBreathStage.setText(R.string.m_info_hold);

                        if (hold_count == 0) {
                            hold_count = hold * 1000;
                            stage = Stage.EXHALE;
                        }
                        break;
                    case EXHALE:  // 呼气
                        exhale_count -= 100;
                        pos--;
                        // 更新进度条 呼气
                        seekBar.setProgress(pos * division_back);

                        txtBreathCount.setText(String.valueOf(exhale_count / 1000.0));
                        txtBreathStage.setText(R.string.m_info_exhale);

                        if (exhale_count == 0) {
                            exhale_count = exhale * 1000;
                            stage = Stage.INHALE;
                        }

                        breath_cur++;
                        break;
                }

            }

            @Override
            public void onFinish() {
                // 暂停时，不计数
                if (status == Status.PAUSE) return;
                // 手指动作
                try {
                    finger_cur = fingers.get(fingerIndex);  // 索引溢出
                    finger_cur.run(1);
                } catch (IndexOutOfBoundsException e) {
                    Toast.makeText(getApplication(), "Out of bounds, L307", Toast.LENGTH_LONG).show();
                    btnStop.callOnClick();
                }
                // 动作图像
                imgFinger.setImageResource(finger_cur.get_drawable());
                // 阶段： 手指动作
                txtFingerStage.setText(String.format(locale, "%s: %d, %s",
                        getString(R.string.m_finger_stage),
                        fingerIndex,
                        finger_cur.getStage()));

                // 进度： 动作次数
                seekBars.get(fingerIndex).setProgress(finger_cur.getCycle_count());
                action_left.get(fingerIndex).setText(finger_cur.getActionLeft());
                // 进度： 单次扳指
                circleSeekBar.setValue(finger_cur.getDuration_cur());

                if (finger_cur.isFinished()) {
                    // 显示结束
                    action_left.get(fingerIndex).setText(R.string.m_info_finished);
                    fingerIndex++;
                }  // if

                if (fingerIndex > 1) {
                    // 结束
                    btnStop.callOnClick();
                    // 播放鼓励动画
                } else {
                    // 重复定时器
                    timer.start();
                }
                // on finish
            }
        };

        //
        Scon = new ServiceConnection() {

            public void onServiceConnected(ComponentName name, IBinder binder) {
                mServ = ((MusicService.ServiceBinder) binder).getService();
            }

            public void onServiceDisconnected(ComponentName name) {
                mServ = null;
            }
        };

        doBindService();
    }


    void doBindService() {
        bindService(new Intent(this, MusicService.class), Scon, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }

    void doUnbindService() {
        if (mIsBound) {
            unbindService(Scon);
            mIsBound = false;
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    // 菜单相应
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        // 运行时，不响应菜单

        Intent intent;
        switch (item.getItemId()) {
            case R.id.menu_brief:
                intent = new Intent(MainActivity.this, AboutActivity.class);
                startActivity(intent);
                break;

            case R.id.menu_support:
                intent = new Intent(MainActivity.this, SupportActivity.class);
                startActivity(intent);
                break;

            case R.id.menu_tutorial_finger:
                intent = new Intent(MainActivity.this, FingerActivity.class);
                startActivity(intent);
                break;

            case R.id.menu_tutorial_breathe:
                intent = new Intent(MainActivity.this, BreatheActivity.class);
                startActivity(intent);
                break;

            case R.id.menu_profile:
                intent = new Intent(MainActivity.this, ProfileActivity.class);
                intent.putExtra("profile", ProfileData);
                startActivity(intent);
                break;

            case R.id.menu_setting_clock:
                intent = new Intent(MainActivity.this, SettingClockActivity.class);
                intent.putExtra("clock", ClockData);
                startActivityForResult(intent, REQUEST_CLOCK);
                break;

            case R.id.menu_setting_level:
                intent = new Intent(MainActivity.this, SettingLevelActivity.class);
                intent.putExtra("level", BreathData);
                startActivityForResult(intent, REQUEST_LEVEL);
                break;

            case R.id.menu_setting_music:
                intent = new Intent(MainActivity.this, SettingMusicActivity.class);
                intent.putExtra("music", MusicData);
                startActivityForResult(intent, REQUEST_MUSIC);
        }
        return true;
    }

    // 闹钟
    private void ClockAlarm() {

        // 取时间
        Iterator iterator = ClockData.entrySet().iterator();
        int i = 0;
        HashMap.Entry entry;
        String s;
        String[] time;
        Intent intent;
        PendingIntent clockIntent;
        Calendar calendar = Calendar.getInstance();

        while (iterator.hasNext()) {
            entry = (HashMap.Entry) iterator.next();
            s = entry.getValue().toString();
            if (s.contains(":")) {
                time = s.split(":");
            } else {
                continue;
            }
            // clock
            intent = new Intent(context, AlarmReceiver.class);
            intent.putExtra("hour", Integer.parseInt(time[0]));
            intent.putExtra("minute", Integer.parseInt(time[1]));
            clockIntent = PendingIntent.getBroadcast(context, i, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            i++;

            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
            calendar.set(Calendar.MINUTE, Integer.parseInt(time[1]));
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                    AlarmManager.INTERVAL_DAY, clockIntent);
            clockArray.add(clockIntent);

        }
    }


    // 读取数据
    private void readData() {
        // 数据读取
        Profile profile = new Profile(getApplication());
        // 闹钟
        ClockData = new HashMap<>();
        ClockData = profile.readClockData();

        // 呼吸
        BreathData = new HashMap<>();
        BreathData = profile.readBreathData();

        // 音乐数据
        MusicData = new HashMap<>();
        MusicData = profile.readBackgroundMusicData();

        // 档案经验
        ProfileData = new HashMap<>();
        ProfileData = profile.readProfileData();

    }


    // 后退按键
    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - currentBackPressedTime > 3000) {
            currentBackPressedTime = System.currentTimeMillis();
            Toast.makeText(getApplication(), "Press again, exit.", Toast.LENGTH_SHORT).show();
        } else {
            finish();
        }
    }

    // Activity 返回

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CLOCK:
                if (resultCode == RESULT_OK) {
                    // 更新数据
                    ClockData.put("clock_is_on", data.getStringExtra("clock_is_on"));
                    ClockData.put("clock_1", data.getStringExtra("clock_1"));
                    ClockData.put("clock_2", data.getStringExtra("clock_2"));
                    ClockData.put("clock_3", data.getStringExtra("clock_3"));

                    // 保存
                    Profile profile = new Profile(getApplication());
                    profile.writeClockData(new String[]{
                            data.getStringExtra("clock_is_on"),
                            data.getStringExtra("clock_1"),
                            data.getStringExtra("clock_2"),
                            data.getStringExtra("clock_3")
                    });

                    //
                    for (PendingIntent clock : clockArray) {
                        alarmMgr.cancel(clock);
                    }
                    clockArray.clear();
                    // 是否打开闹钟
                    if (ClockData.get("clock_is_on").equals("true")) {
                        ClockAlarm();
                    }
                }
                break;
            case REQUEST_LEVEL:
                if (resultCode == RESULT_OK) {
                    // 更新数据
                    BreathData.put("level", data.getIntExtra("level", 0));

                    BreathData.put("new_inhale", data.getIntExtra("new_inhale", 3));
                    BreathData.put("new_hold", data.getIntExtra("new_hold", 2));
                    BreathData.put("new_exhale", data.getIntExtra("new_exhale", 3));

                    BreathData.put("expert_inhale", data.getIntExtra("expert_inhale", 5));
                    BreathData.put("expert_hold", data.getIntExtra("expert_hold", 3));
                    BreathData.put("expert_exhale", data.getIntExtra("expert_exhale", 5));

                    // 保存
                    Profile profile = new Profile(getApplication());
                    profile.writeBreathData(new int[]{
                            data.getIntExtra("level", 0),
                            data.getIntExtra("new_inhale", 3),
                            data.getIntExtra("new_hold", 2),
                            data.getIntExtra("new_exhale", 3),
                            data.getIntExtra("expert_inhale", 5),
                            data.getIntExtra("expert_hold", 3),
                            data.getIntExtra("expert_exhale", 5),

                    });

                }
                break;
            case REQUEST_MUSIC:
                if (resultCode == RESULT_OK) {
                    is_new_music = true;
                    // 更新
                    MusicData.put("music_volume", data.getStringExtra("music_volume"));
                    MusicData.put("music_file", data.getStringExtra("music_file"));
                    // 保存音乐开关、文件
                    Profile profile = new Profile(getApplication());
                    profile.writeBackgroundMusicData(new String[]{
                            data.getStringExtra("music_volume"),
                            data.getStringExtra("music_file")
                    });
                }

        }  // switch
    }

    // 活动销毁
    @Override
    protected void onDestroy() {
        super.onDestroy();
        doUnbindService();
        //stop
        mServ.stopMusic();
    }

    /*  按钮  */
    // Play 按钮
    public void btnPlayClick(View view) {
        // 启动
        switch (status) {
            case STOP:
                init();
                // 定时器
                if (timer != null) {
                    timer.start();
                }
                status = Status.PLAY;
                break;

            case PAUSE:
                status = Status.PLAY;
                break;
        }

        state_button_update(1, 0, 0);
    }

    // 按钮：暂停
    public void btnPauseClick(View view) {
        if (status == Status.PLAY) {
            status = Status.PAUSE;
            state_button_update(0, 1, 0);
        }
    }


    // 按钮：停止
    public void btnStopClick(View view) {
        if (status == Status.STOP) return;
        // Stop
        status = Status.STOP;
        // 取消定时器
        timer.cancel();

        // 进度条：复位
        barAction_1.setProgress(0);
        barAction_2.setProgress(0);
        circleSeekBar.setValue(0);
        seekBar.setProgress(0);

        imgFinger.setImageResource(R.drawable.dance);  // 停止中画面
        state_button_update(0, 0, 1);

        // 停止时，写息数
        calculate_level();
    }

    private void init() {
        if (timer != null) {
            timer.cancel();
        }
        // 取呼吸间隔数据
        switch (BreathData.get("level")) {
            case 0:
                inhale = BreathData.get("new_inhale");
                hold = BreathData.get("new_hold");
                exhale = BreathData.get("new_exhale");
                break;
            case 1:
                inhale = BreathData.get("expert_inhale");
                hold = BreathData.get("expert_hold");
                exhale = BreathData.get("expert_exhale");
        }

        inhale_count = inhale * 1000;
        hold_count = hold * 1000;
        exhale_count = exhale * 1000;

        division_up = PROGRESSBAR_LENGTH / (inhale * 10);
        division_back = PROGRESSBAR_LENGTH / (exhale * 10);
        pos = 0;
        stage = Stage.INHALE;

        // 手指复位
        fingerIndex = 0;
        fingers.get(0).reset();
        fingers.get(1).reset();

        // 复位： 剩余次数
        action_left_1.setText(R.string.m_info_left_0);
        action_left_2.setText(R.string.m_info_left_1);

        breath_cur = 0;

    }

    // 背景音乐 启动
    private void startMusic() {
        Intent music = new Intent();
        // 取设置的音乐
        String f = MusicData.get("music_file");
        int id_music = getApplication().getResources().getIdentifier(f, "raw", getPackageName());
        // 结果大于0，已选择音乐
        if (id_music > 0) {
            music.putExtra("music_item", id_music);
        }
        music.putExtra("music_volume", Integer.parseInt(MusicData.get("music_volume")));
        music.setClass(this, MusicService.class);
        startService(music);

    }

    // 背景音乐 停止
    private void stopMusic() {
        mServ.pauseMusic();
    }

    // 背景音乐服务是否已经启动
    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    private void calculate_level() {
        int level = ProfileData.get("level");
        int count = breath_cur + ProfileData.get("score");
        if (count > BREATH[level]) {
            ProfileData.put("level", level + 1);
            count -= BREATH[level];
        }
        ProfileData.put("score", count);
        Profile profile = new Profile(this);
        profile.writeProfileData(new Integer[]{level, count});

    }

    // 按钮显示刷新
    private void state_button_update(int play, int pause, int stop) {
        btnPlay.setImageLevel(play);
        btnPause.setImageLevel(pause);
        btnStop.setImageLevel(stop);
    }

    // 音乐打开/关闭
    public void musicOnOffClick(View view) {
        if (music_is_on) {
            music_is_on = false;
            stopMusic();

            imgMusic.setImageResource(R.drawable.music_off);
        } else {
            music_is_on = true;
            if (is_new_music) {
                is_new_music = false;
                startMusic();
            } else {
                if (mServ != null)
                    mServ.resumeMusic();
            }

            imgMusic.setImageResource(R.drawable.music_on);
        }
    }

    // end
}
